#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <windows.h>

#include "IconSwap.h"
#include "VersionInfoSwap.h"
#include "cleaner.h"

#ifdef _DEBUG
#include <iostream>
#include <sstream>
#endif

using namespace std;

int wmain(int argc, wchar_t* argv[]) {
    if(argc < 2) {
        fwprintf(stderr, TEXT(" Usage: \n resswap.exe --icon-swap <Icon File> <Executable File>\n OR: \n"));
        fwprintf(stderr, TEXT(" resswap.exe --version-swap <Property File> <Executable File>\n OR: \n"));
        fwprintf(stderr, TEXT(" resswap.exe --clear-icon\n"));
        return 1;
    }

    std::wstring debug = L"";
    std::wstring args = L"";
    std::wstring icon_swap_arg = L"--icon-swap";
    std::wstring version_swap_arg = L"--version-swap";
    std::wstring clearArg = L"--clear";
    
    for (int i = 1; i < argc; i++) {
        std::wstring argument = argv[i];
        if(argument.find(clearArg, 0) == 0) {
            if(argc != 3) {
                fwprintf(stderr, TEXT(" Usage: resswap.exe --clear-icon <Executable File>\n"));
                return 1;
            }
            if(clear(argv[i + 1])) {
                return 0;
            } else {
                fwprintf(stderr, TEXT("failed\n"));
                return 1;
            }
        } else if (argument.find(icon_swap_arg, 0) == 0) {
            if (argc != 4) {
                fwprintf(stderr, TEXT(" Usage: resswap.exe --icon-swap <Icon File> <Executable File>\n"));
                return 1;
            }

            wprintf(L"Icon File Name: %s\n", argv[i + 1]);
            wprintf(L"Executable File Name: %s\n", argv[i + 2]);

            if (ChangeIcon(argv[i + 1], argv[i + 2]) == true) {
                return 0;
            } else {
                fwprintf(stderr, TEXT("failed\n"));
                return 1;
            }
        } else if (argument.find(version_swap_arg, 0) == 0) {
            if (argc != 4) {
                fwprintf(stderr, TEXT(" Usage: resswap.exe --version-swap <Property File> <Executable File>\n"));
                return 1;
            }

            fwprintf(stdout, TEXT("Resource File Name: %s\n"), argv[i + 1]);
            fwprintf(stdout, TEXT("Executable File Name: %s\n"), argv[i + 2]);

            VersionInfoSwap vs(argv[i + 1], argv[i + 2]);

            if (vs.PatchExecutable()) {
                return 0;
            } else {
                fwprintf(stderr, TEXT("failed\n"));
                return 1;
            }
        } else {
            args = args + L" \"" + argv[i] + L"\"";
        }
    }

    return 0;
}